<?php
include_once dirname(__FILE__) . '/php/bkend/GalleryCategory.php';


class GalleryBackend extends Backend{
	
	public static $modName = "Категории";
	private $content;
	private $tplPath;
	
	public function __construct(){
		
		$this->tplPath = dirname(__FILE__) . "/tpl/bkend/";
		
		if(isset($_GET['act']) && $_GET['act'] == 'addCategory'){
			$this->buildManageCategory();
		}
		elseif(isset($_GET['act']) && $_GET['act'] == 'delCategory' && isset($_GET['id']) && FormValidator::IsInt($_GET['id'])){
			$this->delGallery($_GET['id']);
		}
		elseif(isset($_GET['act']) && $_GET['act'] == 'addPhoto'){
			$this->buildAddPhoto();
		}
		elseif(isset($_GET['act']) && $_GET['act'] == 'showPhoto' && isset($_GET['id']) && FormValidator::IsInt($_GET['id'])){
			$this->showPhoto($_GET['id']);
		}
		elseif(isset($_GET['act']) && $_GET['act'] == 'delPhoto' && isset($_GET['id']) && FormValidator::IsInt($_GET['id'])){
			$this->delPhoto($_GET['id']);
		}
		else{
			$this->buildIndex();
		}
	}
	
	private function buildIndex(){
		
		$categories = new GalleryCategory();
		$tpl_row = file_get_contents($this->tplPath . "category_row.htm");
		$rows = "";
		
		foreach ($categories->getCategories() as $k => $val){
			
			$rows .= strtr($tpl_row,
				array(
				'{NAME}' => $val['name'],
				'{IMAGE}' => $val['crop_img'],
				'{ID}' => $val['id'],
				'{COUNT}' => $val['count'],
					)
				);
		}
		
		$this->content = strtr(file_get_contents($this->tplPath . "index.htm"),
			array(
			'{TR}' => $rows,
				)
			);
	}
	
	
	private function buildManageCategory(){
		
		$auto = new AutosaverFiles('_data/gallery/', '_data/gallery/tmp/');
		$auto->setActiveTemplate("<a href='/", "' target='_blank'>Изображение</a>");
		
		if(isset($_GET['id']) && FormValidator::IsInt($_GET['id'])){
			$id = $_GET['id'];
			
			$selectData = mysql_fetch_assoc(mysql_query("SELECT * FROM tb_gallery WHERE id = {$id}"));
			$auto->putSavedFiles("img", $selectData['img'], false);
		}
		else{
			$id = 0;
		}
		
		if(isset($_POST['save'])){
			
			$valid = new FormValidator();
			$valid->AddValidator("name", "NotEmptyTrim");
			$valid->AddValidator("weight", "NotEmptyTrim")->AddValidator("weight", "IsInt");
			
			if(!isset($_POST['imgFfAutoSaved'])){
				$valid->AddValidator("img", "IsImage");
			}
			
			if($valid->ValidateFields($_POST)){
				$name = mysql_escape_string($_POST['name']);
				$descr = mysql_escape_string($_POST['descr']);
				
				if(isset($selectData['img']) && $selectData['img'] != '' && $selectData['img'] != $auto->getFilePath('img')){
					if(file_exists($selectData['img']) && is_file($selectData['img'])){
						unlink($selectData['img']);
						unlink($selectData['crop_img']);
					}
				}
				
				$auto->moveAutosavedFile('img');
				
				$cropImg = $this->cropImage($auto->getFilePath('img'), 300, 200);
				
				$q = ($id == 0)?
				"INSERT INTO tb_gallery (name, descr, img, crop_img, weight) VALUES ('{$name}', '{$descr}', '{$auto->getFilePath('img')}', '{$cropImg}', '{$_POST['weight']}')"
				:
				"UPDATE tb_gallery SET name = '{$name}', descr = '{$descr}', img = '{$auto->getFilePath('img')}', crop_img = '{$cropImg}', weight = '{$_POST['weight']}' WHERE id = '{$id}'"
				;
				mysql_query($q);
				
				$auto->_clearTemporaryDir();
				
				header("Location:?");
				exit();
			}
		}
		
		$this->content = file_get_contents($this->tplPath . "categoryForm.htm");
		$fforms = new FormGen($this->content);
		
		if(isset($valid) && is_object($valid)){
			
			$fforms->SetValidator($valid);
			$fforms->SetMarkErrors($valid->GetErrorFields(), '', "<mrk/>");
		}
		
		$fforms->SetFileAutoSaver($auto);
		
		$arr = (sizeof($_POST) == 0 && isset($selectData))?$selectData:$_POST;
		$this->content = $fforms->Out($arr);		
	}
	
	private function delGallery($id){
		
		$q = "SELECT * FROM tb_gallery WHERE id = '{$id}'";
		$data = mysql_fetch_assoc(mysql_query($q));
		
		if(isset($data['id'])){
			
			@unlink($data['img']);
			@unlink($data['crop_img']);
		}
		
		$q ="DELETE FROM tb_gallery WHERE id = {$id}";
		mysql_query($q);
		header("Location:?");
		exit();
	}
	
	private function showPhoto($id){
		
		
		$tpl_row = file_get_contents($this->tplPath . "photo_row.htm");
		$rows = "";
		
		$q = "SELECT * FROM tb_gallery_photo WHERE parent_id = {$id}";
		$r =mysql_query($q);
		
		while ($val = mysql_fetch_assoc($r)){
			
			$rows .= strtr($tpl_row,
				array(
				'{NAME}' => $val['name'],
				'{IMAGE}' => $val['crop_img'],
				'{ID}' => $val['id'],
					)
				);
		}
		
		$this->content = strtr(file_get_contents($this->tplPath . "photos.htm"),
			array(
			'{TR}' => $rows,
				)
			);
		$this->content = strtr($this->content,
			array(
			'{PARENT_ID}' => $id,
				)
			);
	}
	
	private function delPhoto($id){
		
		$q = "SELECT * FROM tb_gallery_photo WHERE id = '{$id}'";
		$data = mysql_fetch_assoc(mysql_query($q));
		
		if(isset($data['id'])){
			
			@unlink($data['img']);
			@unlink($data['crop_img']);
			@unlink($data['crop_img1']);
		}
		
		$q ="DELETE FROM tb_gallery_photo WHERE id = {$id}";
		mysql_query($q);
		header("Location:?act=showPhoto&id={$data['parent_id']}");
		exit();
	}
	
	private function buildAddPhoto(){
		
		if(!FormValidator::IsInt($_GET['pId'])){
			header("Location:/");
			exit();
		}
		
		$auto = new AutosaverFiles('_data/gallery/', '_data/gallery/tmp/');
		$auto->setActiveTemplate("<a href='/", "' target='_blank'>Изображение</a>");
		
		if(isset($_GET['id']) && FormValidator::IsInt($_GET['id'])){
			$id = $_GET['id'];
			
			$selectData = mysql_fetch_assoc(mysql_query("SELECT * FROM tb_gallery_photo WHERE id = {$id}"));
			$auto->putSavedFiles("img", $selectData['img'], false);
		}
		else{
			$id = 0;
		}
		
		if(isset($_POST['save'])){
			
			$valid = new FormValidator();
			$valid->AddValidator("name", "NotEmptyTrim");
			$valid->AddValidator("weight", "NotEmptyTrim")->AddValidator("weight", "IsInt");
			
			if(!isset($_POST['imgFfAutoSaved'])){
				$valid->AddValidator("img", "IsImage");
			}
			
			if($valid->ValidateFields($_POST)){
				
				$name = mysql_escape_string($_POST['name']);
				$descr = mysql_escape_string($_POST['descr']);
				
				if(isset($selectData['img']) && $selectData['img'] != '' && $selectData['img'] != $auto->getFilePath('img')){
					if(file_exists($selectData['img']) && is_file($selectData['img'])){
						unlink($selectData['img']);
						unlink($selectData['crop_img']);
					}
				}
				
				$auto->moveAutosavedFile('img');
				
				$cropImg = $this->cropImage($auto->getFilePath('img'));
				$cropImg1 = $this->cropImage($auto->getFilePath('img'), 900, 600);
				
				$q = ($id == 0)?
				"INSERT INTO tb_gallery_photo (parent_id, name, descr, img, crop_img, crop_img1, weight) VALUES ('{$_GET['pId']}', '{$name}', '{$descr}', '{$auto->getFilePath('img')}', '{$cropImg}', '{$cropImg1}', '{$_POST['weight']}')"
				:
				"UPDATE tb_gallery_photo SET parent_id = '{$_GET['pId']}', name = '{$name}', descr = '{$descr}', img = '{$auto->getFilePath('img')}', crop_img = '{$cropImg}', crop_img1 = '{$cropImg1}', weight = '{$_POST['weight']}' WHERE id = '{$id}'"
				;
				mysql_query($q);
				
				$auto->_clearTemporaryDir();
				
				header("Location:?act=showPhoto&id={$_GET['pId']}");
				exit();
			}
		}
		
		$this->content = file_get_contents($this->tplPath . "photoForm.htm");
		$fforms = new FormGen($this->content);
		
		if(isset($valid) && is_object($valid)){
			
			$fforms->SetValidator($valid);
			$fforms->SetMarkErrors($valid->GetErrorFields(), '', "<mrk/>");
		}
		
		$fforms->SetFileAutoSaver($auto);
		
		$arr = (sizeof($_POST) == 0 && isset($selectData))?$selectData:$_POST;
		$this->content = strtr($fforms->Out($arr),
			array(
			'{PARENT_ID}' => $_GET['pId'],
				)
			);
		
	}
	
	private function cropImage($path, $w = 176, $h = 117){
		
		$img = new ImgWriteText($path);
		
		$p = GalleryBackend::getCropImageName($path, $w, $h);
		
		$img->resizeWithEmptyBorders($w, $h, $p, 255, 255, 255);
		return $p;
	}
	
	public static function getCropImageName($path, $w = 100, $h = 100){
		$p = pathinfo($path);
		
		return $p['dirname'] . "/{$p['filename']}_{$w}x{$h}.{$p['extension']}";
	}
	
	function out(){
		
		return $this->content;
	}
	
}